import type { ComputedRef } from 'vue';

import type { SearchFormActionType, SearchFormPropsInternal } from '../types/searchForm';
import type { AdColumn, TableProps } from '../types/table';

import { computed, onUnmounted, ref, unref } from 'vue';

import { isProdMode } from '@eacloud/utils';

import { FilterGroup } from '#/request';

/**
 * 使用搜索表单
 * @param propsRef 表格选项
 * @param getLoading 获取加载中
 * @returns 搜索表单对象
 */
export function useSearchForm(propsRef: ComputedRef<TableProps>, getLoading: ComputedRef<boolean | undefined>) {
  const formRef = ref<Nullable<SearchFormActionType>>(null);

  /** 注册 */
  function register(instance: SearchFormActionType) {
    isProdMode() &&
      onUnmounted(() => {
        formRef.value = null;
      });
    if (isProdMode() && instance === unref(formRef)) return;

    formRef.value = instance;
  }

  /** 方法 */
  const methods: SearchFormActionType = {
    /** 获取搜索信息 */
    getSearchInfo: () => {
      return unref(formRef)?.getSearchInfo() as FilterGroup;
    },
  };

  /** 搜索窗体属性 */
  const getSearchFormProps = computed((): Partial<SearchFormPropsInternal> => {
    const searchForm = unref(propsRef).searchForm;
    if (!searchForm) {
      return {};
    }
    const { columns } = unref(propsRef);
    const autoSubmitOnEnter = searchForm === true ? undefined : searchForm.autoSubmitOnEnter;
    const submitOnReset = searchForm === true ? undefined : searchForm.submitOnReset;
    return {
      autoSubmitOnEnter,
      submitOnReset,
      loading: unref(getLoading),
      columns: columns
        ? (columns.filter((item) => {
            // !调用filter方法，传入函数，若函数返回值为真，则返回该项，数组列不允许设置搜索
            // // console.log(index);
            return item?.filterable === true && item?.dataType !== 'array';
          }) as AdColumn[])
        : [],
      compact: true,
    };
  });

  return { getSearchFormProps, register, methods };
}
